#include "HttpServer.hpp"

void HttpServer::httpConnectionCall(ConnectionPtr conn) {
    // 解析conn中的buffer的数据，解析并封装为为http请求
    // std::vector<char> raw_data = conn->readFromBuffer();



    // 调用用户对http请求设置的回调函数，返回一个http response。



    // 将http response写回到conn的buffer中
    
    // conn->writeToBuffer(raw_data);

}


void HttpServer::httpMessageCall(ConnectionPtr conn) {
    if (conn -> isWebSocket()) {
        // 说明该连接已经升级为websocket，进行对应的处理
        auto wsd = std::make_shared<WebSocketData>();
        while (!conn->getInputBuffer() -> empty()) {
            if (!wsd->peekBuffer(conn->getInputBuffer())) break;
            wsd->readFromBuffer(conn->getInputBuffer());
            std::cout << wsd -> getOptcode() << std::endl;
            // 如果optcode为8，直接关闭连接
            if (wsd->getOptcode() == 8) {
                if (userWSCloseCall_) (*userWSCloseCall_)(conn);
                conn->closeConnection();
                return;
            }

            // 将websocket data绑定到connection中，交给用户处理
            conn->setWSData(wsd);
            
            if (userMessageCall_) {
                (*userMessageCall_)(conn);
            }
        }
        return ;
    }
    
    // 解析conn中的buffer的数据，解析并封装为为http请求
    while (!conn->getInputBuffer() -> empty()) {
        auto httpRequest = std::make_shared<HttpRequest>();
        if (!httpRequest->peekBuffer(conn->getInputBuffer())) { // 若buffer中没有完整的http请求，则先不处理。
            break;
        }
        httpRequest->parseOneRequset(conn->getInputBuffer());
        if (httpRequest->getState() == ParseState::ParseErr) {
            continue;
        }

        conn->setHttpRequest(httpRequest);
        auto url = httpRequest->getUrl();
        if (routeHandlers_.find(url) != routeHandlers_.end()) {
            (*routeHandlers_[httpRequest -> getUrl()])(conn);
        }

        

    }
}




void HttpServer::start(unsigned short port) {
    tcpServer_.start(port);
}


void HttpServer::setRoute(std::string route, const std::function<void (ConnectionPtr)>& callback){
    auto callbackptr = std::make_shared<std::function<void(ConnectionPtr)>>(callback);
    if (routeHandlers_.find(route) != routeHandlers_.end()) {
        routeHandlers_.erase(route);
    }
    routeHandlers_[route] = callbackptr;
}